package org.example.window;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.example.data.WaterSensor;
import org.example.function.WaterSensorMapFunction;

public class CountWindowProcessDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //env.enableCheckpointing(2000);

        DataStreamSource<String> source = env.socketTextStream("localhost", 9999);
        SingleOutputStreamOperator<WaterSensor> wsSource = source.map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> sensorKS = wsSource.keyBy(value -> value.getId());

        WindowedStream<WaterSensor, String, GlobalWindow> sensorWS = sensorKS
        //        .countWindow(5);//滑动窗口
                .countWindow(5, 2);//滑动窗口。

        SingleOutputStreamOperator<String> process = sensorWS.process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>() {
            @Override
            public void process(String s, ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                long maxTimestamp = context.window().maxTimestamp();
                String maxTime = DateFormatUtils.format(maxTimestamp, "yyyy-MM-dd HH:mm:ss");
                long l = elements.spliterator().estimateSize();
                out.collect("key为：" + s + "窗口的最大时间[" + maxTime + "]中一共有" + l + "条数据,elements:" + elements.toString());
            }
        });

        process.print();
        env.execute("Window API DEMO");
    }
}
